﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace T.Materials.Repository
{
    /// <summary>
    /// 基础仓储
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    public class MBaseRepository<T> : IMRepository<T> where T : class, new()
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        protected readonly MEFDbContext dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbcontext">数据库上下文</param>
        public MBaseRepository(MEFDbContext dbcontext)
        {
            this.dbContext = dbcontext;
        }

        public MEFDbContext DB
        {
            get { return dbContext; }
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> AddAsync(T entity)
        {
            await dbContext.AddAsync(entity);
            return await dbContext.SaveChangesAsync();
        }

        ///// <summary>
        ///// 异步删除数据
        ///// </summary>
        ///// <param name="id">主键ID</param>
        ///// <returns>返回受影响的行数</returns>
        //public async Task<int> DeletedAsync(int id)
        //{
        //    var res = await dbContext.Set<T>().FindAsync(id);
        //    dbContext.Set<T>().re

        //}

        /// <summary>
        /// 获取实体列表
        /// </summary>
        /// <returns>返回实体列表</returns>
        public async Task<List<T>> GetAllAsync()
        {
            return await dbContext.Set<T>().ToListAsync();
        }

        /// <summary>
        /// 根据条件获取实体列表
        /// </summary>
        /// <param name="expre">条件表达式</param>
        /// <returns>返回实体列表</returns>
        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await dbContext.Set<T>().Where(expre).ToListAsync();
        }



        /// <summary>
        /// 根据Id获取实体
        /// </summary>
        /// <param name="id">实体Id</param>
        /// <returns>实体</returns>
        public async Task<T> GetModelAsync(int id)
        {
            return await dbContext.Set<T>().FindAsync(id);
        }

        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> UpdateAsync(T entity)
        {
            dbContext.Set<T>().Update(entity);
            return await dbContext.SaveChangesAsync();
        }


    }
}
